import React, { useState } from 'react';
import styles from './index.less';
import { Button, Card,  Form,   message, Spin,  } from 'antd';
import { history} from '@umijs/max';
import { encryptionAES } from '@/utils/Aes';
import { RegisterByPhone } from '../api';
import { LoginForm, ProFormText } from '@ant-design/pro-components';
import  { LockOutlined, PhoneOutlined, SwitcherOutlined, UserOutlined } from '@ant-design/icons';

const Register: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);

  function isAccount(value: any,type: any) {
    switch (type) {
      case 'phone':
        return /^1\d{10}$/.test(value);
      case 'password':
        return /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/.test(value);
      default:
        return /^\d+$/.test(value);
    }
  }

  const onFinish = async () => {
    setLoading(true);
    const values = {
        username: form.getFieldValue('username'),
        password: encryptionAES(form.getFieldValue('password')),
        phoneNumber: form.getFieldValue('phoneNumber'),
    }
    const res = await RegisterByPhone(values);
    if (res.code === 200) {
        message.success(res.message);
        form.resetFields();
        history.push('/user/login');
    } else {
        message.error(res.message);
    }
    setLoading(false);
}

const formItemLayout = {
  labelCol: { 
    span: 6
  },
  wrapperCol: { 
    span: 16
  }
};

  return (
    <div className={styles.container}>
 <Spin spinning={loading}>
       <div className={styles.content}>
        <Card
        title={
          <a onClick={() => {
            form.resetFields();
            history.push('/user/login');
          }}>
            返回登录
          </a>
        } 
        className={styles.form}
        >
          <div className={styles.registerHeader}>
            <h1>账号注册</h1>
          </div>
      <LoginForm
      form={form}
      name="register"
      onFinish={onFinish}
      layout="horizontal"
      {...formItemLayout}
      submitter={{
        render: () => (
          <Button 
            type="primary"
            onClick={() => form.submit()}
            style={{
              width: "100%",
              height: '42px',
              marginTop: '20px'
            }}
          >
            立即注册
          </Button>
        ),
      }}
    >
              <ProFormText
          className={styles.formSelect}
          name="username"
          label="用户名"
          fieldProps={{
            size: 'large',
            prefix: <UserOutlined />,
          }}
          placeholder={'请输入用户名'}
          rules={[
              {
                required: true,
                message: '请输入用户名',
              },
          ]}
        >
        </ProFormText>
        <ProFormText
          className={styles.formSelect}
          label="手机号码"
          name="phoneNumber"
          fieldProps={{
            size: 'large',
            prefix: <PhoneOutlined />,

          }}
          placeholder={'请输入手机号码'}
          rules={[
              {
                required: true,
                message: '请输入手机号码',
              },
              () => {
                return {
                  validator(_, value) {
                    if (isAccount(value, 'phone') || !value) {
                      return Promise.resolve();
                    }
                    return Promise.reject(new Error('手机号格式错误!'));
                  },
                };
              },
          ]}
        >
        </ProFormText>
        <ProFormText
          className={styles.formSelect}
          label="邮箱"
          name="email"
          fieldProps={{
            size: 'large',
            prefix: <SwitcherOutlined />,
          }}
          placeholder={'请输入用户名'}
          rules={[
              {
                required: true,
                message: '请输入用户名',
              },
          ]}
        >
        </ProFormText>
        <ProFormText.Password
        className={styles.formSelect}
        label="密码"
        name="password"
        fieldProps={{
          size: 'large',
          prefix: <LockOutlined />,
        }}
        placeholder={'请输入密码'}
        rules={[
          {
            required: true,
            message: '密码是必填项！',
          },
          () => {
            return {
              validator(_, value) {
                if (isAccount(value, 'password') || !value) {
                  return Promise.resolve();
                }
                return Promise.reject(new Error('至少八个字符，至少一个字母和一个数字!'));
              },
            };
          },
        ]}
        hasFeedback
      />
        <ProFormText.Password
        className={styles.formSelect}
        label="确认密码"
        name="confirm"
        fieldProps={{
          size: 'large',
          prefix: <LockOutlined />,
        }}
        placeholder={'请确定密码'}
        dependencies={['password']}
        hasFeedback
        rules={[
          {
            required: true,
            message: '密码是必填项！',
          },
         ({ getFieldValue }) => ({
            validator(_, value) {
              if (!value || getFieldValue('password') === value) {
                return Promise.resolve();
              }
              return Promise.reject(new Error('输入的密码不匹配'));
            },
          }),
        ]}
      />

    </LoginForm>
    </Card>
        </div>
        </Spin >
    </div>

  );
};

export default Register;
